package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.ioc.IocFactory;
import com.ioc.IocFactoryInstance;
import com.opensymphony.xwork2.ActionSupport;
import com.util.AppUtil;
import com.util.Page;

public class BaseAction extends ActionSupport{
	private static Log logger = LogFactory.getLog(BaseAction.class);
	private static final long serialVersionUID = 1L;
	/** 系统注入工厂类 */
	public static IocFactory<?> ioc = IocFactoryInstance.getFactoryInstance(); 

	//获取request
	public HttpServletRequest request(){
		return ServletActionContext.getRequest();
	}
	public Object request(String attrName){
		return ServletActionContext.getRequest().getAttribute(attrName);
	}
	public String getParameter(String param){
		return ServletActionContext.getRequest().getParameter(param);
	}
	public void setRequest(String attrName,Object attrValue){
		ServletActionContext.getRequest().setAttribute(attrName, attrValue);
	}
	//获取response
	public HttpServletResponse response(){
		return ServletActionContext.getResponse();
	}
	//获取pageContext
	public PageContext pageContext(){
		return ServletActionContext.getPageContext();
	}
	//根据name取得一个session对象
	public Object session(String name){
		return ServletActionContext.getRequest().getSession().getAttribute(name);
	}
	//设置一个session对象
	public void setSession(String name ,Object value){
		ServletActionContext.getRequest().getSession().setAttribute(name, value);
	}
	//移除session对象
	public void removeSession(String name){
		ServletActionContext.getRequest().getSession().removeAttribute(name);
	}
	/*****
	 * 在value为空的情况下，pro为返回值
	 * 
	 * @param value
	 * @param pro
	 * @param type
	 *            是否把该属性传到页面，0:否，1：是
	 * @return
	 */
	public String getStringValue(String value, String pro, int type) {
		String v = request().getParameter(value);
		if ("" != v && v != null && v.length() > 0) {
			v = v.trim();
			if (type == 1)
				request().setAttribute(value, v);
		} else
			v = pro;

		return v;
	}

	/*****
	 * 从request中获取参数，转换为整形
	 * 
	 * @param key_value
	 * @param v
	 * @param type
	 *            是否把该属性传到页面，0:否，1：是
	 * @return
	 */
	public int getIntValue(String key, int v, int type) {
		String key_value = request().getParameter(key);
		int value = 0;
		try {
			if ((key_value == null) || (key_value.trim().length() == 0)) {
				return v;
			}

			if (key != null) {
				value = Integer.parseInt(String.valueOf(key_value).trim());
				if (type == 1)
					request().setAttribute(key, value);
			}
		} catch (NumberFormatException exc) {
			throw new NumberFormatException(key_value);
		}
		return value;
	}

	/*******
	 * 从request中获取参数，转换日期类型
	 * 
	 * @param key
	 * @param type
	 * @return
	 */
	public Date getDateValue(String key, String type) {
		Date str = null;
		try {
			String key_value = request().getParameter(key);
			if ((key_value == null) || (key_value.trim().length() == 0)) {
				return new Date();
			}
			str = AppUtil.StringToDate(key_value, type);
			request().setAttribute(key, key_value);
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(),ex);
		}
		return str;

	}

	/**
	 * 设置分页
	 * 
	 * @return
	 */
	public Page setPage(int size) {
		Page p = new Page();
		p.setEveryPage(size);
		p.setCurrentPage(getIntValue("pageNo", 0, 0));
		return p;
	}

	/******
	 * 设置分页
	 * 
	 * @param size
	 *            每页数
	 * @param page_No
	 *            第几页
	 * @return
	 */
	public Page setPage(int size, int page_No) {
		Page p = new Page();
		p.setEveryPage(size);
		p.setCurrentPage(page_No);
		return p;
	}

	/*****
	 * json处理
	 * 
	 * @param str
	 */

	public void outJsonObject(Object obj) {
		outJsonString(JSONObject.fromObject(obj).toString());
	}

	public void outJsonString(String str) {
		response().setContentType("text/javascript;charset=UTF-8");
		outString(str);
	}

	/******
	 * json数组
	 * 
	 * @param array
	 */
	public void outJsonArray(Object array) {
		outJsonArray(JSONArray.fromObject(array).toString());
	}

	/******
	 * xml写入
	 * 
	 * @param xmlStr
	 */
	public void outXMLString(String xmlStr) {
		response().setContentType("application/xml;charset=UTF-8");
		response().setHeader("Cache-Control", "no-cache");
		outString(xmlStr);
	}

	/****
	 * 写入
	 * 
	 * @param str
	 */
	public void outString(String str) {
		PrintWriter out = null;
		try {
			out = response().getWriter();
			out.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}
	}

	/*****
	 * html转换
	 * 
	 * @param str
	 * @return
	 */
	public static String toHtmlValue(String str) {
		if (str != null) {
			str = str.replaceAll("&", "&amp;")
					.replaceAll("<", "&lt;")
					.replaceAll(">", "&gt;")
					.replaceAll("\n", "<br/>")
					.replaceAll("\r", "")
					.replaceAll("\\s{2,}", " ")
					.replaceAll("\"", "&quot;");
			return str;
		}
		return "";
	}
	
	/****
	 * html转换
	 * 
	 * @param str
	 * @return
	 */
	public static String toTextAreaValue(String str) {
		if (str != null) {
			str = str.replaceAll("\r", "")
			.replaceAll("\n", "")
			.replaceAll("&lt;", "<")
			.replaceAll("&gt;", ">")
			.replaceAll("<br/>","\n")
			.replaceAll("&amp;", "&")
			.replaceAll("&nbsp;", " ")
			.replaceAll("&quot;","\"");
			return str;
		}
		return "";
	}
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	/**
	 * 绕过Template,直接输出内容的简便函数. 
	 */
	protected void render(final String text, final String contentType) {
		try {
			response().setContentType(contentType);
			response().getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
	}
	// 绕过jsp/freemaker直接输出文本的函数

	/**
	 * 直接输出文本,默认编码为UTF-8.
	 */
	protected void renderText(final String text) {
		render(text, "UTF-8");
	}

	/**
	 * 直接输出文本.
	 */
	protected void renderText(final String text, final String encoding) {
		render(text, "text/plain;charset=" + encoding);
	}

	/**
	 * 直接输出HTML,默认编码为UTF-8.
	 */
	protected void renderHtml(final String html) {
		render(html, "UTF-8");
	}

	/**
	 * 直接输出HTML.
	 */
	protected void renderHtml(final String html, final String encoding) {
		render(html, "text/html;charset=" + encoding);
	}

	/**
	 * 直接输出XML,默认编码为UTF-8.
	 */
	protected void renderXML(final String xml) {
		render(xml, "UTF-8");
	}

	/**
	 * 直接输出XML.
	 */
	protected void renderXML(final String xml, final String encoding) {
		render(xml, "text/xml;charset=" + encoding);
	}
	
	/******
	 * 对象转换为json ，使用GSON处理
	 * @param obj 对象
	 */
	public void Object2Json(Object obj){
		try{
			Gson gson = new Gson();
			outString(gson.toJson(obj));
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error("BaseAction 中 gson2String 方法转换出错："+ex.getMessage());
		}
	}
	/*****
	 * json 转换为对象，使用GSON处理
	 * @param str          json
	 * @param entryclass   对象
	 * @return
	 */
	public Object Json2Object(String str, Class<?> entryclass){
		Object obj=null;
		try{
			Gson gson = new Gson();
			obj=gson.fromJson(str, entryclass);
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error("BaseAction 中 gson2String 方法转换出错："+ex.getMessage());
		}
		return obj;
	}
}
